/**
 * yeahmobi.com Inc.
 * Copyright © 2014 YeahMobi | All Rights Reserved.
 */

package com.ndp.fb.rdb.db.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.ndp.fb.rdb.api.PagePermissionRdbService;
import com.ndp.fb.rdb.db.DaoTemplate;
import com.ndp.fb.rdb.db.impl.mapper.DefaultRowMapper;
import com.ndp.fb.rdb.model.PagePermission;
import com.ndp.fb.redis.api.RedisClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.PreparedStatementCreator;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Title: PagePermissionRdbServiceImpl.java
 * @Copyright: Copyright © 2015
 * @Description:
 * @Company: yeahmobi
 * @Created on 下午3:11:20
 * @author giser.yang
 */
@Service
public class PagePermissionRdbServiceImpl extends DaoTemplate implements PagePermissionRdbService {

    @Autowired
    private RedisClient redisClient;
	/**
	 * @discription
	 * @author giser.yang
	 * 创建时间 2015年6月18日 下午3:11:20
	 * @param pageId
	 * @param fbUserId
	 * @return
	 * @see com.ndp.fb.rdb.api.PagePermissionRdbService#getPagePermissions(java.lang.Long, java.lang.Long)
	 */

	@Override
	public List<PagePermission> getPagePermissions(Long pageId, Long fbUserId) {
		String sql = "select * from fb_userpermissions_pages where page_id = ? and fb_user_id = ?";
		return getJdbcTemplate().query(sql, new Object[]{pageId,fbUserId}, DefaultRowMapper.autoRowMapper(PagePermission.class));
	}

	/**
	 * @discription
	 * @author giser.yang
	 * 创建时间 2015年6月18日 下午3:11:20
	 * @param fbUserId
	 * @return
	 * @see com.ndp.fb.rdb.api.PagePermissionRdbService#getPagePermissionsByFbUserId(java.lang.Long)
	 */

	@Override
	public List<PagePermission> getPagePermissionsByFbUserId(Long fbUserId) {
		String sql = "select * from fb_userpermissions_pages where fb_user_id = ?";
		return getJdbcTemplate().query(sql, new Object[]{fbUserId}, DefaultRowMapper.autoRowMapper(PagePermission.class));
	}

	/**
	 * @discription
	 * @author giser.yang
	 * 创建时间 2015年6月18日 下午3:11:20
	 * @param pageId
	 * @param fbUserId
	 * @param fbBusinessId
	 * @return
	 * @see com.ndp.fb.rdb.api.PagePermissionRdbService#getPagePermission(java.lang.Long, java.lang.Long, java.lang.Long)
	 */

	@Override
	public PagePermission getPagePermission(Long pageId, Long fbUserId,
			Long fbBusinessId) {
		String sql = "select * from fb_userpermissions_pages where page_id = ? and fb_user_id = ? and fb_business_id = ?";
		return findOne(sql, new Object[]{pageId,fbUserId,fbBusinessId}, DefaultRowMapper.autoRowMapper(PagePermission.class));
	}

	/**
	 * @discription 已经增加了redis乐观锁不会重复入库
	 * @author giser.yang
	 * 创建时间 2015年6月18日 下午3:11:20
	 * @param pagePermission
	 * @return
	 * @see com.ndp.fb.rdb.api.PagePermissionRdbService#saveorupdatePagePermission(com.ndp.fb.rdb.model.PagePermission)
	 */

	@Override
	public Long saveorupdatePagePermission(PagePermission pagePermission) {
		String key = "PAGEPERMISSION"+pagePermission.getFbBusinessId()+pagePermission.getFbUserId()+pagePermission.getPageId();
		if(!redisClient.setNx(key, pagePermission)){
			return 0L;
		}
		try {
			redisClient.expire(key, 5, TimeUnit.SECONDS.name());
			//这里加个乐观锁保证不会重复录入
			PagePermission pagePermission1 = this.getPagePermission(pagePermission.getPageId(), pagePermission.getFbUserId(), pagePermission.getFbBusinessId());
			if (pagePermission1 != null) {
				this.updatePagePermission(pagePermission);
				return pagePermission1.getId();
			} else {
				return this.savePagePermission(pagePermission);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}finally{
			redisClient.delete(key);
		}
		return 0L;
	}
	private Long savePagePermission(PagePermission pagePermission) {
		return saveResultId(pagePermission);
	}

	private Integer updatePagePermission(final PagePermission pagePermission) {
		return getJdbcTemplate().update(new PreparedStatementCreator() {
			public PreparedStatement createPreparedStatement(Connection con)
					throws SQLException {
				String sql = "UPDATE fb_userpermissions_pages SET "
						+ "role = ?,status = ? where page_id = ? and fb_user_id = ? and fb_business_id = ?";
				PreparedStatement ps = con.prepareStatement(sql);
				ps.setObject(1, pagePermission.getRole());
				ps.setObject(2, pagePermission.getStatus());
				ps.setObject(3, pagePermission.getPageId());
				ps.setObject(4, pagePermission.getFbUserId());
				ps.setObject(5, pagePermission.getFbBusinessId());
				return ps;
			}
		});
	}
	/**
	 * @discription
	 * @author giser.yang
	 * 创建时间 2015年6月18日 下午3:11:20
	 * @param pagePermission
	 * @return
	 * @see com.ndp.fb.rdb.api.PagePermissionRdbService#deletePagePermission(com.ndp.fb.rdb.model.PagePermission)
	 */

	@Override
	public Integer deletePagePermission(final PagePermission pagePermission) {
		return getJdbcTemplate().update(new PreparedStatementCreator() {
			public PreparedStatement createPreparedStatement(Connection con)
					throws SQLException {
				String sql = "delete from fb_userpermissions_pages where 1 = 1 and page_id = ? and fb_user_id = ? and fb_business_id = ?";
				PreparedStatement ps = con.prepareStatement(sql);
				ps.setObject(1, pagePermission.getPageId());
				ps.setObject(2, pagePermission.getFbUserId());
				ps.setObject(3, pagePermission.getFbBusinessId());
				return ps;
			}
		});
	}

	/**
	 * @discription
	 * @author giser.yang
	 * 创建时间 2015年6月18日 下午3:11:20
	 * @param pageId
	 * @return
	 * @see com.ndp.fb.rdb.api.PagePermissionRdbService#getPagePermissions(java.lang.Long)
	 */

	@Override
	public List<PagePermission> getPagePermissions(Long pageId) {
		String sql = "select * from fb_userpermissions_pages where page_id = ?";
		return getJdbcTemplate().query(sql, new Object[]{pageId}, DefaultRowMapper.autoRowMapper(PagePermission.class));
	}

	/**
	 * @discription
	 * @author giser.yang
	 * 创建时间 2015年6月19日 下午1:15:00
	 * @return
	 * @see com.ndp.fb.rdb.api.PagePermissionRdbService#getPagePermissionNotInPages()
	 */

	@Override
	public List<PagePermission> getPagePermissionNotInPages() {
		String sql = "SELECT * FROM fb_userpermissions_pages WHERE page_id NOT IN (SELECT fb_page_id FROM page)";
		return getJdbcTemplate().query(sql, DefaultRowMapper.autoRowMapper(PagePermission.class));
	}

	@Override
	public Integer deletePagePermissionByFbUserId(final Long fbUserId) {
		return getJdbcTemplate().update(new PreparedStatementCreator() {
			public PreparedStatement createPreparedStatement(Connection con)
					throws SQLException {
				String sql = "delete from fb_userpermissions_pages where fb_user_id = ?";
				PreparedStatement ps = con.prepareStatement(sql);
				ps.setObject(1, fbUserId);
				return ps;
			}
		});
	}
}
